package cn.newtouch.filters;


import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Component
public class LoginCheckFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    //执行顺序 越小越先 一般不为负数
    @Override
    public int filterOrder() {
        return 0;
    }

    //返回值为true 说明需要权限校验 为false 说明不需要权限校验 放行
    //返回结果决定 是否要执行run方法
    @Override
    public boolean shouldFilter() {
        //通过路径判断是否访问受限资源
        //1.获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String url = request.getRequestURI();
        //如果url包含login register
        if(url.endsWith("/login")|| url.endsWith("/register")) {
            // /login , /register 不需要做登录检查，返回false
            return false;
        }
        //要做登录检查的返回true 走run方法
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1.获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //2.获取响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //3.获取token，并判断是否为null
        String token = request.getHeader("token");

        //4.如果为空，返回失败信息，map ，将map编码集utf8
        if (!StringUtils.hasLength(token)) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("success", false);
            map.put("message", "nologin");

            //设置编码集
            response.setContentType("application/json;charset=utf-8");

            //把map转成json字符串，写到浏览器
            String strJsonMap = JSONObject.toJSONString(map);

            //5.writer到前端
            try {
                response.getWriter().write(strJsonMap);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //阻止filter继续往后执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);

        }
        return null;
    }

}
